package com.kycxika.app.adapter;

import android.app.DownloadManager;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.resource.drawable.GlideDrawable;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.GlideDrawableImageViewTarget;
import com.kycxika.app.R;
import com.kycxika.app.bean.downBean;
import com.kycxika.app.utils.APPUtil;
import com.kycxika.app.view.CircleImageView;
import com.kycxika.app.view.ProgressButton;

import java.util.ArrayList;

/**
 * Created by kyc on 2017/5/12.
 */
public class StarSiveAdapter extends BaseAdapter {
    private final Context mContext;
    private final ArrayList<downBean> mData;
    private DownloadManager mManager;
    private long mEnqueue;
    private ViewHolder mHolder;
    private onSelectorItem onSelector;
    private View inflate;

    public StarSiveAdapter(Context context, ArrayList<downBean> downBeen) {
        this.mContext = context;
        this.mData = downBeen;
    }

    @Override
    public int getCount() {
        return mData.size();
    }

    @Override
    public downBean getItem(int position) {
        return mData.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    public Handler handler = new Handler() {

        private ProgressButton button;

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 100:
                    int fraction = msg.arg1;
                    int pos = msg.arg2;
                    if ((Integer) mHolder.btnDown.getTag() == pos) {
                        //mHolder.btnDown.setProgress(fraction);
                        mHolder.progress.setProgress(fraction);
                    }
                    break;
                case 101:
                    int posi = msg.arg2;
                    if ((Integer) mHolder.btnDown.getTag() == posi) {
                        mHolder.btnDown.setProgress(100);
                        mHolder.btnDown.setText("完成");
                    }
                    break;
            }
        }
    };

    private Boolean isPause = false;

    @Override
    public View getView(final int position, View convertView, final ViewGroup parent) {
        mHolder = null;
        if (convertView == null) {
            inflate = View.inflate(mContext, R.layout.star_list_item, null);
            convertView = inflate;
            mHolder = new ViewHolder(convertView);
            convertView.setTag(mHolder);
        } else {
            mHolder = (ViewHolder) convertView.getTag();
        }
        final downBean downBean = mData.get(position);
        Glide.with(mContext)
                .load(downBean.getImageUrl())
                .diskCacheStrategy(DiskCacheStrategy.ALL)//缓存多个尺寸
                .thumbnail(0.1f)//先显示缩略图  缩略图为原图的1/10
                .error(R.drawable.ic_launcher)
                .into(new GlideDrawableImageViewTarget(mHolder.image) {
                    @Override
                    public void onLoadStarted(Drawable placeholder) {
                        super.onLoadStarted(placeholder);
                    }

                    @Override
                    public void onLoadFailed(Exception e, Drawable errorDrawable) {
                        super.onLoadFailed(e, errorDrawable);
                    }

                    @Override
                    public void onResourceReady(GlideDrawable resource, GlideAnimation<? super GlideDrawable> animation) {
                        super.onResourceReady(resource, animation);
                    }
                });

        mHolder.name.setText(downBean.getName());
        mHolder.version.setText(downBean.getNewVersionCode());
        mHolder.version.setVisibility(View.VISIBLE);
        mHolder.progress.setVisibility(View.GONE);
        mHolder.btnDown.setText("下载");
        mHolder.btnDown.initState();

        mHolder.btnDown.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mHolder.btnDown.setTag(position);
                mHolder.progress.setVisibility(View.VISIBLE);
                mHolder.version.setVisibility(View.GONE);
                //if((Integer)mHolder.btnDown.getTag() == position) {
                APPUtil.removeOldApk();
                mHolder.btnDown.isShowProgressNum(true);
                //downApk(downBean.getDownUrl(),downBean.getName());
                if (onSelector != null) {
                    onSelector.onClickSeleterItem(downBean, position);
                }
                //mHolder.btnDown.setTag(position+1);
                if (!mHolder.btnDown.isFinish()) {
                    mHolder.btnDown.toggle();
                }
                // }

                //mHolder.btnDown.setProgress(MainActivity.instance.getProgressDown());
            }
        });
        mHolder.btnDown.setOnStateListener(new ProgressButton.OnStateListener() {
            @Override
            public void onFinish() {
                isPause = true;
                // mHolder.btnDown.setText("完成");
            }

            @Override
            public void onStop() {
                isPause = true;
                mHolder.btnDown.setText("继续");
            }

            @Override
            public void onContinue() {
                isPause = false;
                //mHolder.btnDown.setText("暂停");
            }
        });
        return convertView;
    }

    public void setOnSelect(onSelectorItem onSelectorItem) {
        this.onSelector = onSelectorItem;
    }

    public interface onSelectorItem {

        void onClickSeleterItem(downBean path, int position);

    }

   /* private boolean isBindService;

    private ServiceConnection conn = new ServiceConnection() {

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            DownLoadService.DownloadBinder binder = (DownLoadService.DownloadBinder) service;
            DownLoadService downloadService = binder.getService();

            //接口回调，下载进度
            downloadService.setOnProgressListener(new DownLoadService.OnProgressListener() {
                @Override
                public void onProgress(float fraction) {
                    // LogUtil.i(TAG, "下载进度：" + fraction);
                    mHolder.btnDown.setProgress((int) (fraction * 100));

                    //判断是否真的下载完成进行安装了，以及是否注册绑定过服务
                    if (fraction == DownLoadService.UNBIND_SERVICE && isBindService) {
                        mContext.unbindService(conn);
                        isBindService = false;
                       // MToast.shortToast("下载完成！");
                        mHolder.btnDown.setText("下载完成！");
                    }
                }
            });
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    };*/


   /* public void downApk(String versionUrl, String versionName) {
        mManager = (DownloadManager) mContext.getSystemService(Context.DOWNLOAD_SERVICE);
        //创建下载任务
        DownloadManager.Request request = new DownloadManager.Request(Uri.parse(versionUrl));
        request.setAllowedOverRoaming(false);//漫游网络是否可以下载
        //设置文件类型,下载完成可以自动打开
        MimeTypeMap singleton = MimeTypeMap.getSingleton();
        String extension = singleton.getMimeTypeFromExtension(MimeTypeMap.getFileExtensionFromUrl(versionUrl));
        request.setMimeType(extension);
        //在通知栏显示,默认就是显示的
        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE);
        request.setVisibleInDownloadsUi(true);
        //在sdcard卡下设置一个下载文件夹
        request.setDestinationInExternalPublicDir("/download", versionName + ".apk");
        //将下载请求加入下载队列

        //加入下载队列后会给该任务返回一个long型的id，
        //通过该id可以取消任务，重启任务等等，看上面源码中框起来的方法
        mEnqueue = mManager.enqueue(request);
        //注册广播接收者,监听下载状态
        mContext.registerReceiver(receiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
    }

    private BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            mHolder.checkDownLoad();
            notifyDataSetChanged();
        }
    };*/

    class ViewHolder {
        CircleImageView image;
        TextView name;
        TextView version;
        ProgressButton btnDown;
        ProgressBar progress;

        public ViewHolder(View view) {
            name = (TextView) view.findViewById(R.id.star_item_name);
            image = (CircleImageView) view.findViewById(R.id.star_item_image);
            version = (TextView) view.findViewById(R.id.star_item_version);
            btnDown = (ProgressButton) view.findViewById(R.id.star_item_btn);
            progress = (ProgressBar) view.findViewById(R.id.progress);
        }

        /*public void checkDownLoad() {
            DownloadManager.Query query = new DownloadManager.Query();
            query.setFilterById(mEnqueue);
            Cursor cursor = mManager.query(query);
            if (cursor.moveToFirst()) {
                int cursorInt = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS));
                switch (cursorInt) {
                    case DownloadManager.STATUS_RUNNING:
                        btnDown.setText("正在下载...");
                        break;
                    case DownloadManager.STATUS_PAUSED:
                        btnDown.setText("暂停下载...");
                        break;
                    case DownloadManager.STATUS_SUCCESSFUL:
                        btnDown.setText("下载成功...");
                        break;
                    case DownloadManager.STATUS_FAILED:
                        btnDown.setText("下载失败...");
                        break;
                    case DownloadManager.STATUS_PENDING:
                        btnDown.setText("延迟下载...");
                        break;
                }
            }
        }*/
    }
}
